package com.shop.cereshop.agent.utils;

import com.shop.cereshop.agent.dao.user.CereAgentPrivateDAO;
import com.shop.cereshop.commons.utils.RandomStringUtil;
import com.shop.cereshop.agent.dao.user.CereAgentRoleDAO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;


@Component
@Slf4j
public class InvitationCodeGenerator {

    @Autowired
    CereAgentPrivateDAO cereAgentPrivateDAO;

    // 生成非靓号账号
    public String generateNonNiceNumbers(int count) {
        int maxAttempts = 0;
        // 防止无限循环
        final int maxAttempt = 1000;

        // 先生成足够的候选账号
        List<String> candidates = new ArrayList<>();
        // 生成10倍数量作为候选
        while (candidates.size() < count * 10 && maxAttempts < maxAttempt) {
            // 生成6为数根据时间戳生成的邀请码
            String randomCode = RandomStringUtil.getRandomCode(6, 6);
            candidates.add(randomCode);
            maxAttempts++;
        }

        try {
            // 查询数据库中已存在的账号
            if (cereAgentPrivateDAO != null && !candidates.isEmpty()) {
                List<String> existingAccounts = cereAgentPrivateDAO.selectListByInvitationCode(candidates);
                // 从候选账号中移除已存在的账号
                candidates.removeAll(existingAccounts);
            }

            // 如果还有候选账号，返回第一个
            if (!candidates.isEmpty()) {
                return candidates.get(0);
            }
        } catch (Exception e) {
            log.error("数据库查询异常: " + e.getMessage());
            // 如果数据库查询失败，直接从候选账号中返回第一个
            if (!candidates.isEmpty()) {
                return null;
            }
        }

        return null;
    }


}

